<?php


defined('BASEPATH') OR exit('No direct script access allowed');

class Notify extends Base_Controller 
{
    private static $data = array();
    protected $models=['orderlist_model','refund_model','user_model','notice_model'];
    public function __construct()
    {
        parent::__construct();        
        
    }
    //下单通知回调
    public function index()
    {       
        try{
            require_once "/application/libraries/wxpay/WeixinPay.php";
            
            $pay=new WeixinPay();
            $post_data=$pay->notify();
            $trade_no=$post_data['out_trade_no'];
            $where['trade_no']=$trade_no;
            $order=$this->orderlist_model->getWhereRow($where);
            //write_file('log.text',json_encode($post_data));
            
            if($post_data['return_code']=='SUCCESS'){
                /*
                 * 首先判断，订单是否已经更新为ok，因为微信会总共发送8次回调确认
                 * 其次，订单已经为ok的，直接返回SUCCESS
                 * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
                 */
                if($order['status']==2){        //已付
                    $pay->return_success();
                }else{
                    
                    if($this->orderlist_model->updateWhere($where,['status'=>2])){
                        
                        $pay->return_success();
                    }
                    
                }
            }else{
                echo '微信支付失败';
            }
            
        }catch (Exception $e) {
            exit();
        }
    }
    
   
    //退款通知回调
    public function refund(){
        require_once "/application/libraries/wxpay/WeixinPay.php";        
        $pay=new WeixinPay();
        
        $data=$pay->refund_notify();
        
        
        $refund_no=@$data['out_refund_no'];
        $where['refund_no']=$refund_no;
        $refund=$this->refund_model->getWhereRow($where);
        if(!$refund) exit();
        
        if($refund['status']==5){        //已付            
            $pay->return_success();
        }else{        
            if($this->refund_model->updateWhere($where,['status'=>5])){                
                $pay->return_success();
            }
        }
    }
    
    
}
